package edu.xcdq.dao.impl;

import edu.xcdq.bean.News;
import edu.xcdq.dao.BaseDao;
import edu.xcdq.dao.NewsDao;
import org.junit.jupiter.api.Test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NewsDaoImpl extends BaseDao implements NewsDao {
    @Override
    public List<News> getPageNews(int pageNo , int pageSize ) {
        ArrayList<News> newsList = new ArrayList<>();

        String sql = "select * from news_detail order by createDate desc limit ?,?";
        // 分页参数
        pageNo = (pageNo-1)*pageSize;
        Object[] params = {pageNo , pageSize };
        ResultSet rs = executeSQL(sql, params);
        try{
            while (rs.next()) {
                Integer id = rs.getInt("id");
                String title = rs.getString("title");
                String summary = rs.getString("summary");
                String content = rs.getString("content");
                String author = rs.getString("author");
                Date createDate = rs.getDate("createDate");

                News resultNews = new News();
                resultNews.setId(id);
                resultNews.setTitle(title);
                resultNews.setSummary(summary);
                resultNews.setContent(content);
                resultNews.setAuthor(author);
                resultNews.setCreateDate(createDate);
                // 将遍历之后的结果存入分页数组中
                newsList.add(resultNews);
            }
        } catch (SQLException e) {
            e.printStackTrace();

        }
        return newsList;
    }

    @Override
    public int getTotalCount(){
        int totalCount=0;
        String sql="select count(*) from news_detail";
        Object[] params={};
        ResultSet rs=this.executeSQL(sql, params);
        try {
            while(rs.next()){
                totalCount=rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            this.closeAll();
        }
        return totalCount;
    }

    @Test
    public void test(){
        int totalCount = getTotalCount();
        System.out.println(totalCount);
    }


}
